<?php

namespace App\Models;

use Dcat\Admin\Traits\HasDateTimeFormatter;

use Illuminate\Database\Eloquent\Factories\HasFactory;
use Illuminate\Database\Eloquent\Model;
use Illuminate\Notifications\Notifiable;
use Laravel\Sanctum\HasApiTokens;
use Illuminate\Foundation\Auth\User as Authenticatable;
class User extends Authenticatable
{
    use HasApiTokens, HasFactory, Notifiable, HasDateTimeFormatter;

    protected $primaryKey = 'id';
    /**
     * The attributes that are mass assignable.
     *
     * @var array<int, string>
     */
    protected $fillable = [
        'name',
        'email',
        'password',
        'mobile',
        'avatar'
    ];

    /**
     * The attributes that should be hidden for serialization.
     *
     * @var array<int, string>
     */
    protected $hidden = [
        'password',
//        'remember_token',
//        'created_at',
//        'updated_at'
    ];

    /**
     * The attributes that should be cast.
     *
     * @var array<string, string>
     */
    protected $casts = [
        'email_verified_at' => 'datetime',
    ];

    /**
     * @param $where
     * @return mixed
     */
    public function getUser($where)
    {
        return self::where($where)->first();
    }

    public function extend()
    {
        return $this->hasOne(UsersExtend::class, 'uid', 'id');
    }

    /**
     * @param $data
     * @return mixed
     */
    public function createUser($data)
    {

        $user = self::create($data);
        UsersExtend::create(['uid'=>$user->id]);
//        UserInfo::create(['uid' => $user->uid]);
//        if (isset($data['invite_one']) && $data['invite_one'] > 0) {
//            $coins = (new Data())->getConfig('sign_integral');
//            (new UserCoin())->createCoin($data['invite_one'], $user->uid, UserCoin::INCOME, $coins, UserCoin::INTEGRAL, $title = '邀请好友');
//        }
        return $user;
    }

    /**
     * 获取token
     * @param $user
     * @return array
     */
    public function token($user)
    {
        $result['uid'] = $user->id;
        $result['name'] = $user->name;
        $result['mobile'] = $user->mobile;
        $result['email'] = $user->email;
        $result['access_token'] = $user->createToken($user->id)->plainTextToken;;
//        $result['token_type'] = 'bearer';
//        $result['expires_in'] = auth()->factory()->getTTL() * 60;
        return $result;
    }

    /**
     * 我/ta的粉丝
     * @param $uid
     * @param $type
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getFans($uid,$type){
        if($type==1){
            $where=['status'=>1,'xinli'=>1];
        }elseif($type==2){
            $where=['status'=>1,'zhanbu'=>1];
        }elseif($type==3){
            $where=['status'=>1,'qingting'=>1];
        }else{
            $where=['status'=>1,'xinli'=>0,'zhanbu'=>0,'qingting'=>0];
        }
        $ids=UserFocus::where(['focus_id'=>$uid])->paginate(10)->pluck('user_id');
        $my_ids=UserFocus::where(['user_id'=>$uid])->pluck('focus_id')->toArray();
        $list = self::query()->where($where)->whereIn('id',$ids)->get();
        foreach ($list as &$v){
            $v['is_focus']=in_array($v->id,$my_ids)?1:0;
        }
        return $list;
    }

    /**
     * 我/ta的关注
     * @param $uid
     * @param $type
     * @return \Illuminate\Database\Eloquent\Builder[]|\Illuminate\Database\Eloquent\Collection
     */
    public function getFocus($uid,$type){
        if($type==1){
            $where=['status'=>1,'xinli'=>1];
        }elseif($type==2){
            $where=['status'=>1,'zhanbu'=>1];
        }elseif($type==3){
            $where=['status'=>1,'qingting'=>1];
        }else{
            $where=['status'=>1,'xinli'=>0,'zhanbu'=>0,'qingting'=>0];
        }
        $ids=UserFocus::where(['user_id'=>$uid])->paginate(10)->pluck('focus_id');
        $list = self::query()->where($where)->whereIn('id',$ids)->get();
        foreach ($list as &$v){
            $v['is_focus']=self::getFocusStatus($uid,$v->id);
        }
        return $list;
    }

    public function fans(){
        return $this->hasMany(UserFocus::class,'user_id','id');
    }

    public function teacherList($type,$skill,$therapy,$crowd,$city,$price,$date,$gender,$consult_types,$order){
        if($type==1){
            $where=['status'=>1,'xinli'=>1];
        }elseif($type==2){
            $where=['status'=>1,'zhanbu'=>1];
        }elseif($type==3){
            $where=['status'=>1,'qingting'=>1];
        }else{
            $where=['status'=>1,'xinli'=>0,'zhanbu'=>0,'qingting'=>0];
        }

        if($city) $where['city']=$city;
        if($gender) $where['gender']=$gender;

        $query= self::query()->select(['users.*','e.*'])
            ->join('users_extend as e','users.id','=','uid')
            ->where($where);


        $query->with(['teacherOrder'=>function($query){
                $query->select(['id','user_id','appoint_id','comment','grade']);
                $query->with(['user'=>function($query){
                    $query->select(['id','name','avatar']);
                }]);
            }
        ]);

        if($price){
            $price_arr= explode('-',$price);
            $query->whereBetween('text_price',[$price_arr[0],$price_arr[1]]);
        }

        if($date){
            $query->whereDate('take_order_day_begin','<',$date);
            $query->whereDate('take_order_day_end','>',$date);
        }

        if($skill){
            $query->whereRaw('FIND_IN_SET(?,skill)',[$skill]);
        }
        if($therapy){
            $query->whereRaw('FIND_IN_SET(?,therapy)',[$therapy]);
        }
        if($crowd){
            $query->whereRaw('FIND_IN_SET(?,crowd)',[$crowd]);
        }
        if($consult_types){
            $query->whereRaw('FIND_IN_SET(?,consult_types)',[$consult_types]);
        }

        if($order){
            if($order==1) {
                $query->orderBy('text_price');
            }
            if($order==2) {
                $query->orderBy('order_num', 'desc');
            }
        }
        return $query->paginate(10);
    }


    public  static function getFocusStatus($uid,$t_uid){
        $my=UserFocus::where(['user_id'=>$uid,'focus_id'=>$t_uid])->first();
        $t=UserFocus::where(['user_id'=>$t_uid,'focus_id'=>$uid])->first();
        if($my && $t) return 3;
        if($my) return 1;
        if($t) return 2;
        return 0;
    }

    public static function getRate($num){
        if($num >= 1000){
            $rate=1.3;
        }elseif ($num >= 500){
            $rate=1.2;
        }elseif ($num >= 100){
            $rate=1.1;
        }else{
            $rate=1;
        }

        return $rate;
    }

    public function teacherOrder(){
        return $this->hasOne(OrderAppoint::class,'appoint_id','id');
    }

}
